package org.example.servlet;

import org.example.entity.Favorite;
import org.example.entity.User;
import org.example.service.FavoriteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/favorite")
public class FavoriteServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(FavoriteServlet.class);
    private FavoriteService favoriteService;

    @Override
    public void init() throws ServletException {
        favoriteService = new FavoriteService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info("开始处理/favorites请求");

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            logger.warn("用户未登录，重定向到登录页");
            response.sendRedirect("login.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        logger.info("获取到用户信息: {}", user);

        try {
            logger.info("开始查询用户ID {} 的收藏内容", user.getId());
            List<Favorite> favorites = favoriteService.getUserFavorites(user.getId());
            logger.info("查询到 {} 条收藏记录", favorites.size());

            if (favorites.isEmpty()) {
                logger.warn("收藏记录为空，但数据库中有记录，请检查查询条件");
            }

            request.setAttribute("favoriteContents", favorites);
            logger.info("设置request属性 favoriteContents: {}", favorites);

            RequestDispatcher dispatcher = request.getRequestDispatcher("/favorites.jsp");
            logger.info("准备转发到favorites.jsp");
            dispatcher.forward(request, response);

        } catch (Exception e) {
            logger.error("处理收藏请求时发生错误", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(false);

        try {
            if (session == null || session.getAttribute("user") == null) {
                out.print("{\"success\":false,\"message\":\"未登录\"}");
                return;
            }

            String action = validateAction(request.getParameter("action"));
            int contentId = validateContentId(request.getParameter("contentId"));
            String contentType = validateContentType(request.getParameter("contentType"));

            User user = (User) session.getAttribute("user");
            int userId = user.getId();

            boolean success = false;
            String message = "";

            if ("add".equals(action)) {
                Favorite favorite = new Favorite();
                favorite.setUserId(userId);
                favorite.setContentId(contentId);
                favorite.setContentType(contentType);

                success = favoriteService.addFavorite(favorite);
                message = success ? "收藏成功" : "收藏失败：已收藏该内容";
            } else if ("remove".equals(action)) {
                success = favoriteService.removeFavorite(userId, contentId, contentType);
                message = success ? "取消收藏成功" : "取消收藏失败：未收藏该内容";
            }

            out.print(String.format("{\"success\":%b,\"message\":\"%s\"}", success, message));

        } catch (Exception e) {
            logger.error("收藏操作异常", e);
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }

    private String validateAction(String action) throws IllegalArgumentException {
        if (action == null || !(action.equals("add") || action.equals("remove"))) {
            throw new IllegalArgumentException("无效的操作类型，应为add或remove");
        }
        return action;
    }

    private int validateContentId(String contentIdParam) throws IllegalArgumentException {
        if (contentIdParam == null || contentIdParam.trim().isEmpty()) {
            throw new IllegalArgumentException("内容ID不能为空");
        }
        try {
            return Integer.parseInt(contentIdParam);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("内容ID必须是数字");
        }
    }

    private String validateContentType(String contentType) throws IllegalArgumentException {
        if (contentType == null || contentType.trim().isEmpty()) {
            throw new IllegalArgumentException("内容类型不能为空");
        }
        return contentType;
    }
}